import org.w3c.dom.css.Counter;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo_1107 {
    public static void main(String[] args) throws InterruptedException{
        Counter1107 counter = new Counter1107();

        //创建两个线程对一个变量进行累加
        Thread t1 = new Thread(()->{
            for (int i=0;i<50000;i++){
                //加读锁
                counter.increase();
                //加写锁
                counter.increase1();
            }
        });

        //线程2
        Thread t2 = new Thread(()->{
            for (int i=0;i<50000;i++){
                counter.increase();
                counter.increase1();
            }
        });

        //启动线程
        t1.start();
        t2.start();

        //等待线程执行完成
        t1.join();
        t2.join();

        //查看运行结果
        System.out.println("count = "+counter.count); //count < 200000
    }
}


class Counter1107{
    //多线程环境中修改变量加volatile
    public volatile int count = 0;
    //定义一个读写锁对象
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /*
    * 加读锁存在线程安全问题
    **/
    public void increase(){
        //读锁对象
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        try {
            //加读锁
            readLock.lock();
            count++;
        }finally {
            //释放锁
            readLock.unlock();
        }
    }

    /*
    * 加写锁
    * */
    public void increase1(){
        //写锁对象
        ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        try {
            //加写锁
            writeLock.lock();
            count++;
        }finally {
            //释放锁
            writeLock.unlock();
        }
    }
}
